import http from 'http';
import express from 'express';
//import logger from 'morgan';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import 'babel-polyfill';
import Payload from './models/Payload';
// import productManagerRest from './api/ProductManagerRest';
// import seckillManagerRest from './api/SeckillManagerRest';
import RedisRest from './api/RedisRest';
import providerRest from './api/providerRest';
import test from './test';
import middlewareStatus from './services/middlewareStatus';
// import cron from 'cron';
let app = express();
app.server = http.createServer(app);
// var cronJob = require("cron").CronJob;  
// //每秒钟执行一次  
// let i = 0,c=0;
// logger
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// api router
app.use('/seckill/redis/api/v1/', RedisRest()); 
app.use('/seckill/provider/api/v1/', providerRest()); 
app.use('/test', test()); // for test

// smartstack 健康检查
app.get('/health', (req, res , next) => {
    if(middlewareStatus.isHealth()){
        res.json(new Payload());
    }else{
        next(new Error("Unable to connect to the middleware"));
    }

});

// catch 404 and forward to error handler
app.use( (req, res, next) => {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use( (err, req, res, next) => {
        res.status(err.status || 500);
        res.json( new Payload ({ error: err }, err.status || 500 , err.message));
    });
}

// production error handler
// no stacktraces leaked to user
app.use( (err, req, res, next) => {
    res.status(err.status || 500);
    res.json( new Payload ({ error: err }, err.status || 500 , err.message));
});

//uncaughtException
process.on ('uncaughtException' , (err) => {
    console.error(`Caught exception: ${err}`) ;
});

app.server.listen(process.env.PORT || 3000);

console.log(`Started on port ${process.env.PORT || 3000}`);


export default app;
